#import "PolyvVideoPlugin.h"
#import "LiveVideoViewFactory.h"
#import "VideoViewFactory.h"
#import <PLVLiveAPI/PLVLiveConfig.h>
#import <PLVVodSDK/PLVVodSDK.h>

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

@implementation PolyvVideoPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
        methodChannelWithName:@"plugins.polyv/util"
              binaryMessenger:[registrar messenger]];
    PolyvVideoPlugin* instance = [[PolyvVideoPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
    //注册插件
    //注册 LiveVideoViewFactory
    //plugins.polyv/live 为flutter 调用此 textLabel 的标识
    [registrar registerViewFactory:[[LiveVideoViewFactory alloc] initWithMessenger:registrar.messenger] withId:@"plugins.polyv/live"];
    [registrar registerViewFactory:[[VideoViewFactory alloc] initWithMessenger:registrar.messenger] withId:@"plugins.polyv/video"];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"playerConfig" isEqualToString:call.method]) {
      NSDictionary *argsMap = call.arguments;
      NSString *_config = argsMap[@"config"];
//      NSString *_aesKey = argsMap[@"aesKey"];
//      NSString *_iv = argsMap[@"iv"];
      NSString *_appId = argsMap[@"appId"];
      NSString *_appSecret = argsMap[@"appSecret"];
      [self initSDKForLiveWithAppId:_appId andAppSecret:_appSecret];
      [self initSDKForLiveWithConfig:_config];
  } else if ([@"getFirstImage" isEqualToString:call.method]) {
      // 获取点播首帧封面
      NSDictionary *argsMap = call.arguments;
      NSString *_vid = argsMap[@"vid"];
      if ([@"" isEqualToString:_vid]) result(@"");
      [PLVVodVideo requestVideoWithVid:_vid completion:^(PLVVodVideo *video, NSError *error) {
          result(video.snapshot);
      }];
  } else {
    result(FlutterMethodNotImplemented);
  }
}

// 直播SDK初始化
- (void)initSDKForLiveWithAppId:(NSString *)appId andAppSecret:(NSString *)appSecret{
    DLog(@"appId = %@ \n appSecret = %@",appId,appSecret);
    if ([@"" isEqualToString:appId] || [@"" isEqualToString:appSecret]) return;
    [PLVLiveConfig liveConfigWithAppId:appId appSecret:appSecret];
}

// 点播SDK初始化
- (void)initSDKForLiveWithConfig:(NSString *)config{
    DLog(@"接收到的config >>>%@",config);
    if ([@"" isEqualToString:config]) return;
    //使用 PLVVodSettings 进行初始化
    NSError *error = nil;
    PLVVodSettings *settings = [PLVVodSettings settingsWithConfigString:config error:&error];
    settings.logLevel = PLVVodLogLevelAll;
    settings.mutilAccount = YES;
}

@end
